package com.learning.server.design;

import java.util.Enumeration;
import java.util.Vector;

/**
 * 当一个对象变化时，其它依赖该对象的对象都会收到通知，并且随着变化！对象之间是一种一对多的关系。
 */

interface ObserverBase {
    public void update();
}

class Observer1 implements ObserverBase {

    @Override
    public void update() {
        System.out.println("observer1 has received!");
    }
}

class Observer2 implements ObserverBase {

    @Override
    public void update() {
        System.out.println("observer2 has received!");
    }

}


interface Subject {

    /*增加观察者*/
    public void add(ObserverBase observer);

    /*删除观察者*/
    public void del(ObserverBase observer);

    /*通知所有的观察者*/
    public void notifyObservers();

    /*自身的操作*/
    public void operation();
}

abstract class AbstractSubject implements Subject {

    private Vector<ObserverBase> vector = new Vector<ObserverBase>();

    @Override
    public void add(ObserverBase observer) {
        vector.add(observer);
    }

    @Override
    public void del(ObserverBase observer) {
        vector.remove(observer);
    }

    @Override
    public void notifyObservers() {
        Enumeration<ObserverBase> enumo = vector.elements();
        while(enumo.hasMoreElements()){
            enumo.nextElement().update();
        }
    }
}

class MySubject extends AbstractSubject {

    @Override
    public void operation() {
        System.out.println("update self!");
        notifyObservers();
    }

}


public class Observer {

    public static void main(String[] args) {
        Subject sub = new MySubject();
        sub.add(new Observer1());
        sub.add(new Observer2());

        sub.operation();
    }

}
